<!-- 课程管理(模块) => 课程列表(菜单) => 台账操作列(生成签到二维码按钮) => 点开后展示此组件 -->
<template>
  <Dialog v-model="dialogVisible" width="600" :fullscreen="false" @close="handleClose">
    <template #title>
      <div class="w-full text-center text-[20px] font-bold" style="color: var(--el-color-primary)">
        {{ title }}
      </div>
    </template>
    <template v-if="step === 1">
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading">
        <el-form-item :label="t('signLog.fields.endDate')" prop="endDate">
          <el-time-select
            v-model="formData.endDate"
            :placeholder="t('common.selectTextPlaceholder') + t('signLog.fields.endDate')"
            :start="getNextFiveMinuteMark()"
            end="23:30"
            step="00:05"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
    </template>
    <template v-else-if="step === 2">
      <div class="qrcode-wrapper fullscreen">
        <Qrcode :width="qrCodeWidth" :text="signLogIdKey" />
      </div>
    </template>
    <template v-else>
      <div class="h-[100px] flex justify-center items-center">
        <el-icon class="is-loading" size="30">
          <Loading />
        </el-icon>
      </div>
    </template>
    <template v-if="step === 1" #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { SignLogApi, SignLogVO } from '@/api/course/signlog'
import { FormRules } from 'element-plus'
import { CourseAdminRespVO } from '@/api/course/course'
import { Loading } from '@element-plus/icons-vue'
import { Qrcode } from '@/components/Qrcode'
import dayjs from 'dayjs'
import _ from 'lodash-es'

defineOptions({ name: 'GenQR' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  courseId: undefined,
  startDate: undefined,
  endDate: undefined,
  lastSignOut: undefined,
  beLate: undefined,
  num: undefined,
  signInNum: undefined,
  beLateNum: undefined,
  signOutNum: undefined,
  remark: undefined
})
const formRules = reactive<FormRules>({
  startDate: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('signLog.fields.startDate'),
      trigger: 'blur'
    }
  ],
  endDate: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('signLog.fields.endDate'),
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref

const step = ref(0)

const qrCodeWidth = ref(500)

// 当前查看课程信息
const course = ref<CourseAdminRespVO>()

// 生成/刷新二维码用的id
const signLogId = ref('')
// 二维码的机密
const signLogIdKey = ref('')

const title = computed(() => {
  return step.value === 2
    ? !course.value?.needClass
      ? t('course.qrCode.signIn')
      : t('course.qrCode.signOut')
    : t('course.qrCode.title')
})

const getNextFiveMinuteMark = () => {
  const now = dayjs()
  const nextFiveMinute = now.add(5 - (now.minute() % 5), 'minute').startOf('minute')
  return nextFiveMinute.format('HH:mm')
}

/** 打开弹窗 */
const open = async (row: CourseAdminRespVO) => {
  // 记录点击的课程
  course.value = row
  // 归零
  step.value = 0
  // 打开弹窗
  dialogVisible.value = true
  if (row.signLogId) {
    // 有二维码 直接展示
    step.value = 2
    // 保存回显的signLogId
    signLogId.value = row.signLogId
    // 调用刷新二维码接口
    await refresh()
    return
  }
  // 先用row.id去check是否有已存在的二维码 返回来的是signLog对象
  const response = await SignLogApi.checkSignLog(row.id)
  if (!response) {
    // 无二维码 填写结束时间生成一个
    step.value = 1
  } else {
    // 有二维码 直接展示
    step.value = 2
    // 保存回显的signLogId
    signLogId.value = response.id
    // 调用刷新二维码接口
    await refresh()
  }
}

// 提交表单
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 新建流程
    const data = _.cloneDeep(formData.value) as SignLogVO
    data.courseId = course.value!.id
    // data.endDate的格式是 "HH:mm" 变成当前日期的yyyy-MM-dd HH:mm:ss 其中ss用00代替 然后变成Date
    data.endDate = dayjs(`${dayjs().format('YYYY-MM-DD')} ${data.endDate}:00`).valueOf() as any

    // 新建之后返回的是signLogId
    signLogId.value = await SignLogApi.createSignLog(data)
    step.value = 2
    // 刷新二维码就出来了
    await refresh()
  } finally {
    formLoading.value = false
  }
}

// 刷新二维码
let timer
const refreshing = ref(false)
const refresh = async () => {
  if (!signLogId.value) return
  refreshing.value = true
  const key = await SignLogApi.refreshQrCode(signLogId.value)
  signLogIdKey.value = `${import.meta.env.VITE_H5_HOST}/#/pages/signin/index?key=${key}`
  refreshing.value = false

  timer = setTimeout(() => {
    refresh()
  }, 5000)
}

const handleClose = () => {
  resetForm()
  signLogId.value = ''
  signLogIdKey.value = ''
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    courseId: undefined,
    startDate: undefined,
    endDate: undefined,
    lastSignOut: undefined,
    beLate: undefined,
    num: undefined,
    signInNum: undefined,
    beLateNum: undefined,
    signOutNum: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>

<style lang="scss" scoped>
.qrcode-wrapper {
  display: flex;
  height: 500px;
  justify-content: center;
  align-items: center;
}
</style>
